const Koa = require("koa");
const koaStaticCache = require("koa-static-cache");
const path = require("path");
const koaRouter = require("koa-router");

const app = new Koa();
app.use(
  koaStaticCache(path.join(__dirname, `/static`), {
    prefix: "/public", //如果当前请求的url是以/public开始，则作为静态资源请求
    // localhost:3000/public/1.txt 实际上是访问的d:\wx\vue-learning-demo\koa\static\1.txt
  })
);

const router = new koaRouter();

router.get("/", async (ctx, next) => {
  ctx.body = "index page";
});
router.get("/api/user", async (ctx, next) => {
  ctx.body = "user info page";
});
router.post("/api/user", async (ctx, next) => {
  ctx.body = "edit user info page";
});
router.delete("/api/user", async (ctx, next) => {
  ctx.body = "delete user info page";
});

const dynamicRouter = new koaRouter();
dynamicRouter.get("/api/user/:id", async (ctx, next) => {
  ctx.body = `dynamic page ${ctx.params.id}`;
});

app.use(router.routes());
app.use(dynamicRouter.routes());

app.use(async (ctx, next) => {
  console.log("ctx.url", ctx.url);
  await next();
});

app.listen(3000, "localhost");
